"""Follow-up reminders endpoints."""

from __future__ import annotations

from datetime import datetime

from fastapi import APIRouter, Depends, HTTPException, Query, status
from fastapi.responses import JSONResponse
from sqlalchemy.orm import Session

from app.api.deps import get_current_user, get_db
from app.models.user import User
from app.repositories.follow_up_reminder_repository import FollowUpReminderRepository
from app.schemas.follow_up_reminder import (
    FollowUpReminderCreate,
    FollowUpReminderUpdate,
    FollowUpReminderOut,
    FollowUpReminderWithLead,
    FollowUpReminderListOut,
    TodayTasksOut,
)

router = APIRouter(tags=["reminders"])


@router.get("/today-tasks", response_model=TodayTasksOut)
def get_today_tasks(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db),
) -> TodayTasksOut:
    """
    获取今日待办任务.

    Returns:
        TodayTasksOut: 今日待办任务列表及统计
    """
    repo = FollowUpReminderRepository(db)
    tasks = repo.get_today_tasks(assigned_to=current_user.id)

    # 统计
    now = datetime.now()
    pending_count = len([t for t in tasks if t.status == "pending"])
    overdue_count = len([t for t in tasks if t.reminder_time < now and t.status == "pending"])

    # 转换为输出格式
    task_items = []
    for task in tasks:
        task_items.append(
            FollowUpReminderWithLead(
                id=task.id,
                lead_id=task.lead_id,
                visitor_sheet_id=task.visitor_sheet_id,
                reminder_type=task.reminder_type,
                trigger_reason=task.trigger_reason,
                reminder_time=task.reminder_time,
                assigned_to=task.assigned_to,
                notes=task.notes,
                status=task.status,
                sent_at=task.sent_at,
                completed_at=task.completed_at,
                created_at=task.created_at,
                updated_at=task.updated_at,
                lead_name=task.lead.name,
                lead_phone=task.lead.phone,
                assignee_name=task.assignee.full_name,
                assignee_email=task.assignee.email,
            )
        )

    return TodayTasksOut(
        pending_count=pending_count,
        overdue_count=overdue_count,
        tasks=task_items,
    )


@router.get("/", response_model=FollowUpReminderListOut)
def list_reminders(
    status: str | None = Query(None, description="Filter by status (pending/sent/completed/cancelled)"),
    page: int = Query(1, ge=1, description="Page number"),
    page_size: int = Query(50, ge=1, le=200, description="Items per page"),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db),
) -> FollowUpReminderListOut:
    """
    获取跟进提醒列表（分页）.

    Args:
        status: 筛选状态
        page: 页码
        page_size: 每页数量
        current_user: 当前用户
        db: 数据库会话

    Returns:
        FollowUpReminderListOut: 提醒列表
    """
    repo = FollowUpReminderRepository(db)
    skip = (page - 1) * page_size

    reminders, total = repo.get_by_assigned_to(
        assigned_to=current_user.id, status=status, skip=skip, limit=page_size
    )

    # 转换为输出格式
    items = []
    for reminder in reminders:
        items.append(
            FollowUpReminderWithLead(
                id=reminder.id,
                lead_id=reminder.lead_id,
                visitor_sheet_id=reminder.visitor_sheet_id,
                reminder_type=reminder.reminder_type,
                trigger_reason=reminder.trigger_reason,
                reminder_time=reminder.reminder_time,
                assigned_to=reminder.assigned_to,
                notes=reminder.notes,
                status=reminder.status,
                sent_at=reminder.sent_at,
                completed_at=reminder.completed_at,
                created_at=reminder.created_at,
                updated_at=reminder.updated_at,
                lead_name=reminder.lead.name,
                lead_phone=reminder.lead.phone,
                assignee_name=reminder.assignee.full_name,
                assignee_email=reminder.assignee.email,
            )
        )

    return FollowUpReminderListOut(total=total, items=items, page=page, page_size=page_size)


@router.post("/", response_model=FollowUpReminderOut, status_code=status.HTTP_201_CREATED)
def create_reminder(
    payload: FollowUpReminderCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db),
) -> FollowUpReminderOut:
    """
    手动创建跟进提醒.

    Args:
        payload: 创建请求数据
        current_user: 当前用户
        db: 数据库会话

    Returns:
        FollowUpReminderOut: 创建的提醒
    """
    repo = FollowUpReminderRepository(db)
    reminder = repo.create(payload)
    db.commit()
    return FollowUpReminderOut.model_validate(reminder)


@router.put("/{reminder_id}", response_model=FollowUpReminderOut)
def update_reminder(
    reminder_id: int,
    payload: FollowUpReminderUpdate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db),
) -> FollowUpReminderOut:
    """
    更新跟进提醒.

    Args:
        reminder_id: 提醒ID
        payload: 更新数据
        current_user: 当前用户
        db: 数据库会话

    Returns:
        FollowUpReminderOut: 更新后的提醒

    Raises:
        HTTPException: 提醒不存在
    """
    repo = FollowUpReminderRepository(db)
    reminder = repo.update(reminder_id, payload)

    if not reminder:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Reminder not found")

    db.commit()
    return FollowUpReminderOut.model_validate(reminder)


@router.post("/{reminder_id}/complete", response_model=FollowUpReminderOut)
def mark_reminder_complete(
    reminder_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db),
) -> FollowUpReminderOut:
    """
    标记提醒为已完成.

    Args:
        reminder_id: 提醒ID
        current_user: 当前用户
        db: 数据库会话

    Returns:
        FollowUpReminderOut: 已完成的提醒

    Raises:
        HTTPException: 提醒不存在
    """
    repo = FollowUpReminderRepository(db)
    reminder = repo.mark_as_completed(reminder_id)

    if not reminder:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Reminder not found")

    db.commit()
    return FollowUpReminderOut.model_validate(reminder)


@router.delete("/{reminder_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
def delete_reminder(
    reminder_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db),
) -> None:
    """
    删除跟进提醒.

    Args:
        reminder_id: 提醒ID
        current_user: 当前用户
        db: 数据库会话

    Raises:
        HTTPException: 提醒不存在
    """
    repo = FollowUpReminderRepository(db)
    success = repo.delete(reminder_id)

    if not success:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Reminder not found")

    db.commit()
